import router, { constantRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import permissionRouter from '@/router/modules/permission'
import { checkPermission } from '@/utils/permission'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 验证是否有权限
function hasPermission(route, roles) {
  // console.log('3213', roles)
  if (roles.indexOf('super_admin') > -1 || (roles.indexOf('admin') > -1 && route.name !== 'Setting')) {
    return true
    }
  if (route.meta && route.meta.roles) {
      return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}
const whiteList = ['/login', '/forgetPassword', '/resetPassword', '/searchResult'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken && whiteList.indexOf(to.path) === -1) {
    if (to.path === '/login' || to.path === '/forgetPassword' || to.path === '/resetPassword') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
         const data = await store.dispatch('user/getInfo')
		try {
        var getRoutes = baseRoleGetRouters(permissionRouter, [data.userType.toLowerCase()])
        getRoutes = getRoutes.concat({ path: '*', redirect: '/home', hidden: true })

        // return false
        // 4.将生成好的路由addRoutes
        global.antRouter = constantRoutes.concat(getRoutes)
        router.addRoutes(constantRoutes.concat(getRoutes))
        // Object.assign(constantRoutes,getRoutes)
        if ((JSON.stringify(constantRoutes).indexOf(to.path) <= -1 && JSON.stringify(getRoutes).indexOf(to.path) <= -1 && constantRoutes.length) || (!constantRoutes.length && getRoutes.length)) {
          Message({ type: 'warning', message: ' No authority or page is not exit!' })
        }
        // 5.push之后，会重新进入到beforeEach的钩子里,直接进入第一个if判断
        console.log('sd route', constantRoutes, getRoutes, to)
        router.push({ path: to.fullPath })
        // next()
        // NProgress.done()

          // get user info
          // await store.dispatch('user/getInfo')
          next()
        } catch (error) {
          // remove token and go to login page to re-login
         // await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly

      next()
    } else {
      // ?redirect=${to.path}
      next(`/login`)
      NProgress.done()
    }
  }
})

// 根据用户的角色取到该用户对应的路由
function baseRoleGetRouters(allRoutes, roles) {
  // allRoutes是动态路由表
  // roles是取到的用户角色，数组
  const rightRoutes = allRoutes.filter((route, index) => {
    if (hasPermission(route, roles)) {
      if (route.children && route.children.length) {
        route.children = baseRoleGetRouters(route.children, roles)
      }
      return true
    }
    return false
  })
  return rightRoutes
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
